package com.qf.common.utils;

import com.qf.common.exceptions.CheckException;
import com.qf.common.exceptions.UnloginException;
import org.springframework.context.MessageSource;

import java.util.List;


/**
 * 校验工具类
 */
public class CheckUtil {
    private static MessageSource resources;

    public static void setResources(MessageSource resources) {
        CheckUtil.resources = resources;
    }

    public static void check(boolean condition, String msgKey, Object... args) {
        if (!condition) {
            fail(msgKey, args);
        }
    }

    public static void checkLogin(boolean condition, String msgKey, Object... args) {
        if (!condition) {
            failLogin(msgKey, args);
        }
    }

    public static void checkAdoptIsTrue(boolean condition, String msgKey, Object... args) {
        if (condition) {
            fail(msgKey, args);
        }
    }

    public static void check(boolean condition) {
        if (!condition) {
            fail("field.invalid");
        }
    }

    /**
     * 判断字符串时候为null或""
     *
     * @param str
     * @param msgKey
     * @param args
     */
    public static void notEmpty(String str, String msgKey, Object... args) {
        if (str == null || str.isEmpty()) {
            fail(msgKey, args);
        }
    }

    public static void notEmpty(String str, Object... args) {
        if (str == null || str.isEmpty() || str.equals("undefined")) {
            fail("关键词为空", args);
        }
    }

    public static void notNull(Object obj, String msgKey, Object... args) {
        if (obj == null) {
            fail(msgKey, args);
        }
    }

    public static void checkNum(Integer num, Integer max) {
        if (num == null || num > max) {
            fail("分析总数应小于" + max);
        }
    }

    public static void checkArgs(String args, String msgKey) {
        if (!args.contains("-")) {
            fail(msgKey + "条件格式不正确");
        }
    }

    public static void checkList(Object obj) {
        List<Object> list = (List<Object>) obj;
        if (list == null || list.size() == 0) {
            fail("未获取到数据");
        }
    }

    public static void notNull(Object obj) {
        if (obj == null) {
            notNull(obj, "param.is.null");
        }
    }

    private static void fail(String msgKey, Object... args) {
        throw new CheckException(msgKey);
    }

    private static void failLogin(String msgKey, Object... args) {
        throw new UnloginException(msgKey);
    }

}
